package cn.melonlib.cores.commons.comp.dao.impl;

import cn.melonlib.cores.commons.comp.dao.FileSystem;
import cn.melonlib.cores.commons.comp.dao.FileSystemFileReader;
import cn.melonlib.cores.commons.comp.enums.FileStoreType;
import org.apache.commons.io.FileUtils;
import org.apache.tika.Tika;
import org.hibernate.service.spi.ServiceException;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Repository;
import org.springframework.util.StreamUtils;

import javax.annotation.Resource;
import java.io.*;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Repository
public class OperatingSystemFileSystem implements FileSystem {

    @Resource
    private Environment env;

    @Resource
    private Tika tika;

    @Override
    public void store(InputStream in, String path, FileStoreType storeType) throws Exception {
        String root = env.getProperty(storeType.getPath());
        File file = new File(root, path);
        FileUtils.forceMkdirParent(file);
        try (OutputStream out = new FileOutputStream(file)) {
            StreamUtils.copy(in, out);
        }
    }

    @Override
    public FileSystemFileReader<File> read(String path, FileStoreType storeType) throws Exception {
        final File f=new File(env.getProperty(storeType.getPath()),path);
        return new FileSystemFileReader<File>() {
            public InputStream getInputStream() throws IOException {
                return new FileInputStream(f);
            }
            public Long getContentLength() {
                return f.length();
            }

            @Override
            public String getFileName() {
                return f.getName();
            }

            @Override
            public String getFileContentType() {
                try {
                    return tika.detect(f);
                } catch (IOException e) {
                    throw new ServiceException(e.getMessage(),e);
                }
            }

            @Override
            public String getPath() {
                return f.getAbsolutePath();
            }

            @Override
            public File getSource() {
                return f;
            }
        };
    }

    @Override
    public List<File> dir(String path, FileStoreType storeType) throws Exception {
        final File dir=new File(env.getProperty(storeType.getPath()),path);
        if(!dir.exists()){
            throw new FileNotFoundException("没有这个目录");
        }
        return Arrays.stream(dir.listFiles()).collect(Collectors.toList());
    }

    @Override
    public void delete(String path, FileStoreType storeType) throws Exception {
        final File f=new File(env.getProperty(storeType.getPath()),path);
        FileUtils.deleteQuietly(f);
    }
}
